<template>
  <div class="profile-page">
    <div class="page-header">
      <el-button 
        type="text" 
        @click="$router.back()" 
        class="back-btn"
      >
        <el-icon><ArrowLeft /></el-icon>
        {{ $t('common.back') }}
      </el-button>
      <h1>{{ $t('profile.title') }}</h1>
    </div>

    <div class="profile-container" v-loading="loading">
      <!-- 用户头像和基本信息 -->
      <div class="profile-header">
        <div class="avatar-section">
          <div class="avatar-container">
            <el-avatar 
              :size="120" 
              :src="userProfile?.avatar" 
              class="profile-avatar"
            >
              {{ userProfile?.nickname?.charAt(0)?.toUpperCase() || userProfile?.username?.charAt(0)?.toUpperCase() || 'U' }}
            </el-avatar>
            <el-button 
              type="text" 
              class="upload-btn"
              @click="showAvatarUpload = true"
            >
              <el-icon><Camera /></el-icon>
            </el-button>
          </div>
          <div class="user-info">
            <h2>{{ userProfile?.nickname || userProfile?.username || '用户' }}</h2>
            <p class="username">@{{ userProfile?.username }}</p>
            <p class="bio">{{ userProfile?.bio || t('profile.info.notSet') }}</p>
            <div class="user-stats">
              <div class="stat-item">
                <span class="stat-number">{{ userProfile?.login_count || 0 }}</span>
                <span class="stat-label">{{ $t('profile.stats.loginCount') }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ userStats?.favorite_novels_count || 0 }}</span>
                <span class="stat-label">{{ $t('profile.stats.favoriteNovels') }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ userStats?.favorite_characters_count || 0 }}</span>
                <span class="stat-label">{{ $t('profile.stats.favoriteCharacters') }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <div class="action-buttons">
          <el-button type="primary" @click="handleEditProfile">
            <el-icon><Edit /></el-icon>
            {{ $t('profile.editProfile') }}
          </el-button>
          <el-button @click="showPasswordDialog = true">
            <el-icon><Lock /></el-icon>
            {{ $t('profile.changePassword') }}
          </el-button>
        </div>
      </div>

      <!-- 详细信息 -->
      <div class="profile-content">
        <div class="info-section">
          <h3>👤 {{ $t('profile.info.title') }}</h3>
          <div class="info-grid">
            <div class="info-item">
              <label>{{ $t('profile.info.email') }}</label>
              <span>{{ userProfile?.email }}</span>
            </div>
            <div class="info-item">
              <label>{{ $t('profile.info.phone') }}</label>
              <span>{{ userProfile?.phone || $t('profile.info.notSet') }}</span>
            </div>
            <div class="info-item">
              <label>{{ $t('profile.info.gender') }}</label>
              <span>{{ getGenderText(userProfile?.gender) }}</span>
            </div>
            <div class="info-item">
              <label>{{ $t('profile.info.birthday') }}</label>
              <span>{{ userProfile?.birthday || $t('profile.info.notSet') }}</span>
            </div>
            <div class="info-item">
              <label>{{ $t('profile.info.location') }}</label>
              <span>{{ userProfile?.location || $t('profile.info.notSet') }}</span>
            </div>
            <div class="info-item">
              <label>{{ $t('profile.info.registrationDate') }}</label>
              <span>{{ formatDate(userProfile?.created_at) }}</span>
            </div>
          </div>
        </div>
      </div>

    </div>

    <!-- 编辑资料对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑个人资料"
      width="500px"
      :before-close="handleCloseEdit"
    >
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="80px">
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="editForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="个人简介" prop="bio">
          <el-input 
            v-model="editForm.bio" 
            type="textarea" 
            :rows="3"
            placeholder="介绍一下自己吧"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="editForm.gender">
            <el-radio :label="GenderEnum.MALE">男</el-radio>
            <el-radio :label="GenderEnum.FEMALE">女</el-radio>
            <el-radio :label="GenderEnum.OTHER">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="editForm.birthday"
            type="date"
            placeholder="选择生日"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="所在地" prop="location">
          <el-input v-model="editForm.location" placeholder="请输入所在地" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateProfile" :loading="updating">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="showPasswordDialog"
      title="修改密码"
      width="400px"
    >
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="80px">
        <el-form-item label="原密码" prop="old_password">
          <el-input 
            v-model="passwordForm.old_password" 
            type="password" 
            placeholder="请输入原密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="new_password">
          <el-input 
            v-model="passwordForm.new_password" 
            type="password" 
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirm_password">
          <el-input 
            v-model="passwordForm.confirm_password" 
            type="password" 
            placeholder="请确认新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPasswordDialog = false">取消</el-button>
          <el-button type="primary" @click="handleChangePassword" :loading="changingPassword">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 头像上传对话框 -->
    <el-dialog
      v-model="showAvatarUpload"
      title="上传头像"
      width="400px"
    >
      <el-upload
        class="avatar-uploader"
        :show-file-list="false"
        :before-upload="beforeAvatarUpload"
        :http-request="handleAvatarUpload"
        accept="image/*"
      >
        <img v-if="uploadPreview" :src="uploadPreview" class="avatar-preview" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      <div class="upload-tip">
        <p>支持 JPG、PNG 格式，文件大小不超过 2MB</p>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseAvatarUpload">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleConfirmAvatar" 
            :loading="uploadingAvatar"
            :disabled="!uploadFile"
          >
            确认上传
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, Camera, Edit, Lock, User, Select, Clock, Plus 
} from '@element-plus/icons-vue'
import { userApi } from '../services/userApi'
import type { 
  UserProfile, 
  UserStats, 
  UserUpdate, 
  UserPasswordChange
} from '../types/user'
import { GenderEnum } from '../types/user'

// 路由实例
const router = useRouter()
const { t } = useI18n()

// 响应式数据
const loading = ref(false)
const userProfile = ref<UserProfile | null>(null)
const userStats = ref<UserStats | null>(null)

// 对话框状态
const showEditDialog = ref(false)
const showPasswordDialog = ref(false)
const showAvatarUpload = ref(false)

// 表单数据
const editForm = reactive<UserUpdate>({
  nickname: '',
  bio: '',
  phone: '',
  gender: undefined,
  birthday: '',
  location: ''
})

const passwordForm = reactive<UserPasswordChange & { confirm_password: string }>({
  old_password: '',
  new_password: '',
  confirm_password: ''
})

// 头像上传
const uploadFile = ref<File | null>(null)
const uploadPreview = ref('')
const uploadingAvatar = ref(false)

// 加载状态
const updating = ref(false)
const changingPassword = ref(false)

// 表单验证规则
const editRules = {
  nickname: [
    { max: 100, message: '昵称长度不能超过100个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const passwordRules = {
  old_password: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== passwordForm.new_password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 方法
const handleEditProfile = () => {
  // 填充编辑表单
  Object.assign(editForm, {
    nickname: userProfile.value?.nickname || '',
    bio: userProfile.value?.bio || '',
    phone: userProfile.value?.phone || '',
    gender: userProfile.value?.gender,
    birthday: userProfile.value?.birthday || '',
    location: userProfile.value?.location || ''
  })
  showEditDialog.value = true
}

const getGenderText = (gender?: GenderEnum) => {
  const genderMap = {
    [GenderEnum.MALE]: t('profile.info.male'),
    [GenderEnum.FEMALE]: t('profile.info.female'),
    [GenderEnum.OTHER]: t('profile.info.other')
  }
  return gender ? genderMap[gender] : t('profile.info.notSet')
}

const formatDate = (dateString?: string) => {
  if (!dateString) return t('profile.info.unknown')
  return new Date(dateString).toLocaleDateString()
}

const loadUserData = async () => {
  try {
    loading.value = true
    
    // 并行加载用户数据
    const [profileData, statsData] = await Promise.all([
      userApi.getUserProfile(),
      userApi.getUserStats()
    ])
    
    userProfile.value = profileData
    userStats.value = statsData
    
  } catch (error) {
    console.error('加载用户数据失败:', error)
    ElMessage.error('加载用户数据失败')
  } finally {
    loading.value = false
  }
}

const handleCloseEdit = () => {
  showEditDialog.value = false
  // 重置表单
  Object.assign(editForm, {
    nickname: userProfile.value?.nickname || '',
    bio: userProfile.value?.bio || '',
    phone: userProfile.value?.phone || '',
    gender: userProfile.value?.gender,
    birthday: userProfile.value?.birthday || '',
    location: userProfile.value?.location || ''
  })
}

const handleUpdateProfile = async () => {
  try {
    updating.value = true
    const updatedUser = await userApi.updateUserProfile(editForm)
    
    // 更新本地数据
    if (userProfile.value) {
      Object.assign(userProfile.value, updatedUser)
    }
    
    showEditDialog.value = false
    ElMessage.success('个人资料更新成功')
    
  } catch (error) {
    console.error('更新个人资料失败:', error)
    ElMessage.error('更新个人资料失败')
  } finally {
    updating.value = false
  }
}

const handleChangePassword = async () => {
  try {
    changingPassword.value = true
    await userApi.changePassword({
      old_password: passwordForm.old_password,
      new_password: passwordForm.new_password
    })
    
    showPasswordDialog.value = false
    ElMessage.success('密码修改成功')
    
    // 重置表单
    Object.assign(passwordForm, {
      old_password: '',
      new_password: '',
      confirm_password: ''
    })
    
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败')
  } finally {
    changingPassword.value = false
  }
}

const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  // 生成预览
  const reader = new FileReader()
  reader.onload = (e) => {
    uploadPreview.value = e.target?.result as string
  }
  reader.readAsDataURL(file)
  
  uploadFile.value = file
  return false // 阻止自动上传
}

const handleAvatarUpload = () => {
  // 这里不执行上传，只是为了满足el-upload的要求
}

const handleConfirmAvatar = async () => {
  if (!uploadFile.value) return
  
  try {
    uploadingAvatar.value = true
    const avatarUrl = await userApi.uploadAvatar(uploadFile.value)
    
    // 更新本地数据
    if (userProfile.value) {
      userProfile.value.avatar = avatarUrl
    }
    
    handleCloseAvatarUpload()
    ElMessage.success('头像上传成功')
    
    await loadUserData()
    
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  } finally {
    uploadingAvatar.value = false
  }
}

const handleCloseAvatarUpload = () => {
  showAvatarUpload.value = false
  uploadFile.value = null
  uploadPreview.value = ''
}

// 生命周期
onMounted(() => {
  loadUserData()
})
</script>

<style scoped>
.profile-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
}

.back-btn {
  color: #667eea;
  font-weight: 500;
}

.page-header h1 {
  font-size: 24px;
  font-weight: 700;
  color: #1f2937;
  margin: 0;
}

.profile-container {
  max-width: 1000px;
  margin: 0 auto;
}

.profile-header {
  background: white;
  border-radius: 16px;
  padding: 32px;
  margin-bottom: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 24px;
  margin-bottom: 24px;
}

.avatar-container {
  position: relative;
  flex-shrink: 0;
}

.profile-avatar {
  font-size: 48px;
  font-weight: 700;
}

.upload-btn {
  position: absolute;
  bottom: -5px;
  right: -5px;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #667eea;
  color: white;
  border: 3px solid white;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.user-info {
  flex: 1;
}

.user-info h2 {
  font-size: 28px;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 8px;
}

.username {
  color: #667eea;
  font-weight: 500;
  margin-bottom: 12px;
}

.bio {
  color: #6b7280;
  margin-bottom: 20px;
  line-height: 1.5;
}

.user-stats {
  display: flex;
  gap: 32px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 24px;
  font-weight: 700;
  color: #667eea;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #6b7280;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.profile-content {
  display: grid;
  gap: 24px;
}

.info-section,
.status-section {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.info-section h3,
.status-section h3 {
  font-size: 18px;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 20px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item label {
  font-size: 12px;
  font-weight: 500;
  color: #6b7280;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.info-item span {
  font-size: 14px;
  color: #1f2937;
}

.status-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.status-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  border-radius: 12px;
  background: #f9fafb;
}

.status-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #e5e7eb;
  color: #6b7280;
  font-size: 20px;
  transition: all 0.2s ease;
}

.status-icon.active {
  background: linear-gradient(135deg, #10b981, #059669);
  color: white;
}



.status-info p {
  font-size: 14px;
  color: #1f2937;
  margin: 0;
}

.avatar-uploader {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  width: 178px;
  height: 178px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar-preview {
  width: 178px;
  height: 178px;
  object-fit: cover;
}

.upload-tip {
  text-align: center;
}

.upload-tip p {
  color: #6b7280;
  font-size: 12px;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-page {
    padding: 16px;
  }
  
  .avatar-section {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }
  
  .user-stats {
    justify-content: center;
  }
  
  .action-buttons {
    flex-direction: column;
    align-items: center;
  }
  
  .info-grid,
  .status-grid {
    grid-template-columns: 1fr;
  }
}
</style> 